//订单中心
var server = require('../../utils/server');
var common = require('../../utils/common');
const app = getApp();
Page({
  data: {
    orderParam: {
      "status_select": 0,
      "page": 1,
      "count": 10
    },
    orderStatus: 0,
    pageNum: 1,
    orderEmptyTit: "",
    isEmpty: false,
    orderList: [],
    showStorePop: false,
    storeStatusInfo: "",
    curOrderId: "",
    isLocate: true,
    isLogin: true,
    showPhonePop: false,
    showLoginPop: false,
    isDisableReg: false,
    showConfirmOrderPop: false,
    showDeliveryNumberPop: false,
    isClickCompleting: false,
    curDeliveryCompany: '',
    curDeliveryNumber: ''
  },
  onLoad(options = {}) {},
  onShow() {
    this.setData({
      isLocate: app.globalData.isLocate,
      orderStatus: app.globalData.searchOrderStatus
    })
    if (this.data.isLocate) {
      this.getUserInfo();
    } else {
      console.log(221)
    }
  },
  onHide() {
    this.setData({
      showConfirmOrderPop: false,
      showDeliveryNumberPop: false
    })
  },
  getUserInfo() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        var param = {
          "status_select": this.data.orderStatus,
          "page": 1,
          "count": 10
        }
        this.data.orderParam = param;
        this.searchByStatus();
        this.setData({
          showPhonePop: false,
          showLoginPop: false,
          isLogin: true
        })
      },
      fail: res => {
        this.checkRegister();
      }
    })
  },

  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          console.log('未登录')
          this.setData({
            isLogin: false
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              var param = {
                "status_select": this.data.orderStatus,
                "page": 1,
                "count": 10
              }
              this.data.orderParam = param;
              this.searchByStatus();
            }
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          isLogin: false
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  showLoginPop() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            ticketsnum: res.data.coupon_num,
            avatar: res.data.avatar
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              var param = {
                "status_select": this.data.orderStatus,
                "page": 1,
                "count": 10
              }
              this.data.orderParam = param;
              this.searchByStatus();
            }
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },

  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showCheckTel() {
    this.setData({
      showPhonePop: false
    })
    wx.navigateTo({
      url: '../common/register',
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                isLogin: true,
                isDisableReg: false
              })
              var param = {
                "status_select": this.data.orderStatus,
                "page": 1,
                "count": 10
              }
              this.data.orderParam = param;
              this.searchByStatus();
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.getUserInfo();
    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  searchByStatus() {
    common.showLoading();
    common.hideLoading();
    this.data.orderParam.page = 1;
    this.data.pageNum = 1;
    server.postJSON(common.storePath + 'order/lists/', this.data.orderParam, res => {
      if (res.data.errno == "0") {
        if (res.data.data.length > 0) {
          var dataList = [];
          for (var i = 0; i < res.data.data.length; i++) {
            res.data.data[i].toggle = false;
            dataList.push(res.data.data[i])
          }
          this.setData({
            orderList: dataList,
            isEmpty: false
          })
        } else {
          this.setData({
            isEmpty: true
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  switchNav(e) {
    this.setData({
      orderList: []
    })
    this.data.pageNum = 1;
    var orderStatus = e.currentTarget.dataset.status;
    this.setData({
      orderStatus: orderStatus
    })
    var param = {
      "status_select": orderStatus,
      "page": 1,
      "count": 10
    }
    this.data.orderParam = param;
    this.searchByStatus()
  },
  // 取消订单
  cancelOrder(e) {
    var status = e.currentTarget.dataset.status,
      orderid = e.currentTarget.dataset.orderid;
    this.data.curOrderId = orderid;
    if (status == "50") {
      this.setData({
        showDelPop: true
      })
    } else {
      wx.navigateTo({
        url: '../../order/pages/orderCancel?orderId=' + orderid,
      })
    }
  },
  confirmDel() {
    this.setData({
      showDelPop: false
    })
    wx.navigateTo({
      url: '../../order/pages/orderCancel?orderId=' + this.data.curOrderId,
    })
  },
  cancelDel() {
    this.setData({
      showDelPop: false
    })
  },
  orderAgain(e) {
    app.globalData.refreshTag = true;
    app.globalData.isAccount = true;
    var orderId = e.currentTarget.dataset.orderid;
    console.log(app.globalData.longitude, app.globalData.latitude)
    var param = {
      "order_id": orderId,
      "store_id": wx.getStorageSync("storeId"),
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude
    }
    console.log(wx.getStorageSync("storeId"))
    common.getOrderAgain(param);
  },
  //滚动到底部触发事件  
  onReachBottom() {
    console.log(this.data.pageNum)
    let that = this;
    if (that.data.orderList.length > 3 && !that.data.isEmpty) {
      common.showLoading();
      common.hideLoading();
      that.setData({
        pageNum: that.data.pageNum + 1 //每次触发上拉事件，把searchPageNum+1 
      });
      that.getMoreData()
    }
  },
  getMoreData() {
    this.data.orderParam = {
      "status_select": this.data.orderStatus,
      "page": this.data.pageNum,
      "count": 10
    }
    server.postJSON(common.storePath + 'order/lists/', this.data.orderParam, res => {
      console.log(this.data.orderParam)
      console.log(res)
      if (res.data.errno == "0") {
        common.hideLoading();
        if (res.data.data.length > 0) {
          console.log(res.data.data)
          var newData = this.data.orderList;
          newData = newData.concat(res.data.data)
          this.setData({
            orderList: newData
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  pay(e) {
    console.log(e)
    var orderid = e.currentTarget.dataset.orderid;
    this.setData({
      isPayOk: true
    })
    var param = {
      "currency": '63',
      "order_id": orderid
    }
    common.pay(param).then(res => {
      if (res.errno == "0") {
        var outtradeno = res.data.out_trade_no;
        //发起支付
        var payParam = res.data;
        var that = this;
        payParam.complete = function (ret3) {
          common.showLoading("支付中...");
          //支付成功
          var isSuc = ret3.errMsg == 'requestPayment:ok';
          console.log(isSuc)
          wx.reportAnalytics('pay_status', {
            paystatus: isSuc,
            orderid: orderid
          });
          if (isSuc) {
            wx.reportAnalytics('pay_success', {
              paystatus: isSuc,
              orderid: orderid
            });
            server.postJSON(common.storePath + 'order/payrespond/', {
              'out_trade_no': outtradeno
            }, resp => {
              that.setData({
                isPayOk: false
              })
              that.searchByStatus();
            })
          } else {
            that.setData({
              isPayOk: false
            })
            wx.reportAnalytics('pay_fail', {
              paystatus: isSuc,
              orderid: orderid
            });
            wx.showToast({
              title: '支付失败',
              duration: 2000,
              complete: function () {
              }
            });
          }
        }
        wx.requestPayment(payParam);
      } else {
        if (res.errmsg == undefined) {
          common.showToast("数据出错啦T_T，请稍候再试 [-3]");
          time = setTimeout(function () {
            wx.hideToast()
          }, 3500)
        } else if (res.errno == "1000000") {
          this.setData({
            showStorePop: true,
            storeStatusInfo: res.data.status_tip
          })
        } else {
          common.showToast(res.errmsg);
        }
      }
    })
  },
  hidePop() {
    this.setData({
      showStorePop: false
    })
  },
  //下拉刷新
  onPullDownRefresh() {
    this.data.orderParam.page = 1;
    server.postJSON(common.storePath + 'order/lists/', this.data.orderParam, res => {
      if (res.data.errno == "0") {
        // 停止下拉动作  
        wx.stopPullDownRefresh();
        if (res.data.data.length > 0) {
          this.setData({
            orderList: res.data.data,
          })
        } else {
          this.setData({
            isEmpty: true
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  showAllList(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    this.setData({
      ['orderList[' + index + '].toggle']: !this.data.orderList[index].toggle
    })
  },
  goToDetail(e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../order/pages/orderDetail?orderId=' + orderId,
    })
  },
  showDeliveryNumber(e) {
    this.setData({
      curDeliveryCompany: e.currentTarget.dataset.name,
      curDeliveryNumber: e.currentTarget.dataset.number,
      showDeliveryNumberPop: true
    })
  },
  hideDeliveryNumberPop() {
    this.setData({
      showDeliveryNumberPop: false
    })
  },
  copyDeliveryNumber() {
    var that = this;
    wx.setClipboardData({
      data: this.data.curDeliveryNumber,
      success(res) {
        wx.getClipboardData({
          success(res) {
            that.setData({
              showDeliveryNumberPop: false
            })
          }
        })
      }
    })
  },
  showConfirmOrderPop(e) {
    this.data.curOrderId = e.currentTarget.dataset.orderid;
    this.setData({
      showConfirmOrderPop: true
    })
  },
  hideConfirmOrderPop() {
    this.setData({
      showConfirmOrderPop: false
    })
  },
  confirmOrder() {
    this.setData({
      isClickCompleting: true
    })
    server.postJSON(common.storePath + 'order/complete/', {
      "order_id": this.data.curOrderId
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          showConfirmOrderPop: false
        })
        this.searchByStatus();
        setTimeout(() => {
          this.setData({
            isClickCompleting: false
          })
        }, 1000);
      } else {
        this.setData({
          isClickCompleting: false
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  }
})